import numpy as np
import json
import cv2
import pyzbar.pyzbar as pyzbar
import sys

#颜色范围值
_color_dic=[{'color':'red','lower_hsv': [0, 43, 46], 'upper_hsv': [10, 255, 255]},{'color':'red','lower_hsv': [156, 43, 46], 'upper_hsv': [180, 255, 255]},
            {'color':'yellow','lower_hsv': [26, 43, 46], 'upper_hsv': [34, 255, 255]},{'color':'yellow','lower_hsv': [11, 43, 46], 'upper_hsv': [25, 255, 255]},
            {'color':'blue','lower_hsv': [100, 43, 46], 'upper_hsv': [124, 255, 255]}]

#命中规则【整体轮廓面积>4w ,宽高差<50 ，图块白色像素>黑色像素点】
def isOkContours(range_mask):
    range_mask=cv2.dilate(range_mask, None, iterations=2)
    # 只提取整体外部轮廓
    contours, hierarchy = cv2.findContours(range_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    if (len(contours) <= 0):
        return False
    for cnt in contours:
        x, y, w, h = cv2.boundingRect(cnt)
        crop=range_mask[y:(y + h),x:(x+ w)]
        #crop = cv2.dilate(crop, None, iterations=2)
        blackSum=np.sum([crop==0])
        whiteSum = np.sum([crop == 255])
        area = cv2.contourArea(cnt)
        c = abs(w - h)
        if (area >= 40000 and c <= 100 and whiteSum>blackSum):
            return True
    return False


# get all color
def whatColor(img_hsv):
    _checkFlag=False
    for color in _color_dic:
        lower_hsv = np.array(color['lower_hsv'])
        red_upper_hsv = np.array(color['upper_hsv'])
        target_red_mask = cv2.inRange(img_hsv, lowerb=lower_hsv, upperb=red_upper_hsv)
        _checkFlag=isOkContours(target_red_mask)
        if _checkFlag==False:
            continue
        _checkFlag=True
        print(json.dumps({"code": 0, "color":color['color']}, sort_keys=True))
        break
    if _checkFlag==False:
        print(json.dumps({"code": 0, "color": "other"}, sort_keys=True))

def getColorRange(img_hsv,color_lower_hsv,color_upper_hsv):
    lower_hsv = np.array(color_lower_hsv)
    red_upper_hsv = np.array(color_upper_hsv)
    target_red_mask = cv2.inRange(img_hsv, lowerb=lower_hsv, upperb=red_upper_hsv)
    return target_red_mask

# get single color
def isRedCode(img_hsv):
    red_list = [item  for item in _color_dic if item['color']=='red']
    for color in red_list:
        _range = getColorRange(img_hsv, color['lower_hsv'], color['upper_hsv'])
        _checkFlag = isOkContours(_range)
        if _checkFlag == True:
            print(json.dumps({"code": 0, "color": color['color']}, sort_keys=True))
            break

    if _checkFlag ==False:
        return False

# get single color
def isYellowCode(img_hsv):
    yellow_list = [item for item in _color_dic if item['color'] == 'yellow']
    _checkFlag = False
    for color in yellow_list:
        _range = getColorRange(img_hsv, color['lower_hsv'],color['upper_hsv'])
        _checkFlag = isOkContours(_range)
        if _checkFlag == True:
            print(json.dumps({"code": 0, "color": color['color']}, sort_keys=True))
            break
    if _checkFlag ==False:
        return False
# get single blue color
def isBlueCode(img_hsv):
    blue_list = [item for item in _color_dic if item['color'] == 'blue']
    _checkFlag = False
    for color in blue_list:
        _range = getColorRange(img_hsv, color['lower_hsv'],color['upper_hsv'])
        _checkFlag = isOkContours(_range)
        if _checkFlag == True:
            print(json.dumps({"code": 0, "color": color['color']}, sort_keys=True))
            break
    if _checkFlag ==False:
         return False

#识别码
def regRedCode(url):
    org_rbg_img = cv2.imread(url)
    org_rbg_img=cv2.resize(org_rbg_img,(590,1278))
    # cv2.namedWindow("org_rbg_img", cv2.WINDOW_NORMAL)
    # cv2.imshow("org_rbg_img", org_rbg_img)
    barcodes = pyzbar.decode(org_rbg_img)
    codes=[]
    for barcode in barcodes:
        _rect=barcode.rect
        codeImage=org_rbg_img[_rect.top:(_rect.top + _rect.height),_rect.left:(_rect.width + _rect.left)]
        codes.append(codeImage)
    mergeImage=org_rbg_img

    if len(codes)>0:
        mergeImage = np.concatenate((codes), axis=2)

    img_hsv = cv2.cvtColor(mergeImage, cv2.COLOR_BGR2HSV)
    whatColor(img_hsv)
    # isRed=isRedCode(img_hsv)
    # if isRed==True:
    #     print(json.dumps({"code": 0, "color": "red"}, sort_keys=True))
    #     return
    # yellow=isYellowCode(img_hsv)
    # if yellow==True:
    #     print(json.dumps({"code": 0, "color": "yellow"}, sort_keys=True))
    #     return
    # print(json.dumps({"code": 0, "color": "other"}, sort_keys=True))
    return


if __name__ == '__main__':
    a = []
    for i in range(1, len(sys.argv)):
        a.append(sys.argv[i])
    if len(a)<0:
        print(json.dumps({"code": -1, "color": ""}, sort_keys=True))
    regRedCode(a[0])
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()

